package com.wy;

import com.wy.entity.IpEntity;
import com.wy.service.IpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.Date;
import java.util.UUID;

/**
 * 过滤器
 */
@Component
public class IpFilter implements GlobalFilter, Ordered {
    @Autowired
    private IpServiceImpl ipService;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        IpEntity ipEntity=new IpEntity();
        ipEntity.setId(UUID.randomUUID()+"");
        ipEntity.setIp(remoteAddress.getAddress().toString());
        ipEntity.setPort(remoteAddress.getPort()+"");
        ipEntity.setCreateTime(new Date());
        ipService.insertIp(ipEntity);
        System.out.println("ip:" + remoteAddress.getHostName());
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}